using Quartz;
using Quartz.Impl;
using Quartz.Impl.Triggers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Publicuse.Entity;
using Publicuse.Interface;

namespace Publicuse.Util.QuartZ
{
    public class HttpResultfulJob : IJob
    {
        readonly IHttpClientFactory httpClientFactory;

        readonly IMySqlSugarService mySqlSugar;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="httpClientFactory"></param>
        public HttpResultfulJob(IServiceProvider serviceProvider, IHttpClientFactory httpClientFactory, IMySqlSugarService mySqlSugar)
        {
            this.httpClientFactory = httpClientFactory;
            this.mySqlSugar = mySqlSugar;
            //serviceProvider.GetService()
        }
        public async Task Execute(IJobExecutionContext context)
        {
            DateTime dateTime = DateTime.Now;
            QuzrtTaskOptions taskOptions = context.GetTaskOptions();
            string httpMessage = "";
            AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
            if (taskOptions == null)
            {
                return;
            }
            if (string.IsNullOrEmpty(taskOptions.ApiUrl) || taskOptions.ApiUrl == "/")
            {
                return;
            }
            if (taskOptions.status == (int)QuartzJobAction.Normal || taskOptions.status == (int)QuartzJobAction.Run || taskOptions.status == (int)QuartzJobAction.Add)
            {
                try
                {
                    Dictionary<string, string> header = new Dictionary<string, string>();
                    if (!string.IsNullOrEmpty(taskOptions.HeaderData))
                    {
                        header = JsonUtil.JsonToDictionaryString(taskOptions.HeaderData);
                    }
                    var rtype = taskOptions.RequestType?.ToLower() == "get" ? HttpMethod.Get : HttpMethod.Post;
                    QuartzTaskLog taskLog = new QuartzTaskLog()
                    {
                        TaskName=taskOptions.TaskName,
                        qId=taskOptions.Id.ToString().GetIntValue(),
                        BeginDate=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                    };
                    var lId=this.mySqlSugar.InserBackId<QuartzTaskLog>(taskLog,out var msg);
                    if (taskOptions.RequestType.ToLower() == "get")
                    {
                        httpMessage = await httpClientFactory.HttpSendAsync(rtype, taskOptions.ApiUrl, header);
                    }
                    else
                    {
                        httpMessage = await HttpClientUtil.HttpPostAsync(taskOptions.ApiUrl, taskOptions.ParamData, "application/json", "UTF-8", header);
                    }
                    var table = TableAtributeUtil.GetTable<QuzrtTaskOptions>();
                    var tableb = TableAtributeUtil.GetTable<QuartzTaskLog>();
                    var nowtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    var sql = $"update {table} set LastRunTime='{nowtime}' where Id={taskOptions.Id};" +
                        $"update {tableb} set EndDate='{nowtime}',Msg='{httpMessage}' where Id={lId};";
                    this.mySqlSugar.ExecuteSql(sql, null, out var msgb);
                }
                catch (Exception ex)
                {
                    httpMessage = ex.Message;
                }

                try
                {
                    Log log = new Log()
                    {
                        lmodule = "系统任务调度管理",
                        ltype = "分组：【" + taskOptions.GroupName + "】-任务：【" + taskOptions.TaskName + "】",
                        luser = "系统",
                        lsuccess = 1,
                        status = 1,
                        lcontent = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}_{dateTime.ToString("yyyy - MM - dd HH: mm: ss")}地址：【" + taskOptions.ApiUrl + "】,请求方式：【" + taskOptions.RequestType + "】,执行结果：【" + httpMessage + "】"
                    };
                }
                catch (Exception)
                {
                }
            }
            return;
        }
    }
}
